package question_factory;

import java.util.LinkedList;
import java.util.List;

import com.sun.org.apache.xerces.internal.impl.xs.SubstitutionGroupHandler;

import answers.IAnswer;
import answers.MultipleChoiceAnswer;
import answers.TrueFalseAnswer;
import models.AbstractQuestion;
import models.MultipleChoiceQuestion;
import models.TrueFalseQuestion;

public class MultipleChoiceQuestionFactory implements IQuestionFactory
{

	@Override
	public AbstractQuestion createQuestion(String encoding)
	{
		String [] tokens = encoding.split("\\s");
		if(tokens.length < 5)
		{
			return null;
		}
		
		try
		{
			double points = Double.parseDouble(tokens[2]);
			
			int startChoicePos;
			for(startChoicePos = 4; startChoicePos < tokens.length; startChoicePos++)
			{
				if(tokens[startChoicePos].startsWith("(", 0))
				{
					break;
				}
			}
			
			String questionText = new String();
			for(int i = 3; i< startChoicePos; ++i)
			{
				questionText+= tokens[i] + " ";
			}
			
			String choiceSet = tokens[startChoicePos];
			String answerSet = null;
			
			boolean hasAnswer = (tokens.length == startChoicePos + 3);
			if(hasAnswer)
			{
				// this question has an answer
				if(!tokens[startChoicePos + 1].equals("-a"))
				{
					return null;
				}
				answerSet = tokens[startChoicePos + 2];
			}
			
			MultipleChoiceQuestion question = new MultipleChoiceQuestion("Multiple-Choice question", questionText, points);
			boolean res = parseChoices(choiceSet, question);
			if(!res)
			{
				// wrong format
				return null;
			}
			if(hasAnswer)
			{
				List<String> listOfAnswers = parseAnswers(answerSet);
				if(listOfAnswers == null)
				{
					// again, wrong format
					return null;
				}
				IAnswer answer = new MultipleChoiceAnswer(listOfAnswers);
				question.setItsIAnswer(answer);
			}
			return question;
		}
		catch(NumberFormatException e)
		{
			System.out.println("Wrong question format");
			return null;
		}

	}

	private boolean parseChoices(String choiceSet, MultipleChoiceQuestion question)
	{
		if(!choiceSet.startsWith("(") || !choiceSet.endsWith(")"))
		{
			return false;
		}
		// trim parentheses
		choiceSet = choiceSet.substring(1);
		choiceSet = choiceSet.substring(0, choiceSet.length() - 1);
		
		String [] tokens = choiceSet.split(",");
		for(int i = 0; i < tokens.length; ++i)
		{
			question.addChoice(tokens[i]);
		}
		return true;
	}
	
	private List<String> parseAnswers(String answerSet)
	{
		List<String> retval = new LinkedList<String>();
		
		if(!answerSet.startsWith("(") || !answerSet.endsWith(""))
		{
			return null;
		}
		
		// trim parentheses
		answerSet = answerSet.substring(1);
		answerSet = answerSet.substring(0, answerSet.length() - 1);
		
		String [] tokens = answerSet.split(",");
		for(int i = 0; i < tokens.length; ++i)
		{
			retval.add((tokens[i]));
		}
		return retval;
	}
}
